<template>
  <div class="editor-container">
    <!-- 左侧组件区域 -->
    <div class="left-panel">
      <h3>组件</h3>
      <div class="component-list">
        <button class="component-item" @click="addText">添加文本</button>
      </div>
    </div>
    
    <!-- 中间Canvas展示区域 -->
    <div class="center-panel">
      <canvas 
        ref="canvas" 
        width="800" 
        height="600"
        @mousedown="handleMouseDown"
        @mousemove="handleMouseMove"
        @mouseup="handleMouseUp"
        :style="{ cursor: isOverText ? 'pointer' : 'default' }"
      ></canvas>
    </div>
    
    <!-- 右侧属性设置区域 -->
    <div class="right-panel">
      <h3>属性设置</h3>
      <div v-if="selectedTextIndex !== -1" class="property-panel">
        <div class="property-item">
          <label>文本内容:</label>
          <input v-model="text" placeholder="输入文字" />
        </div>
        
        <div class="property-item">
          <label>字体:</label>
          <select v-model="fontFamily">
            <option value="Arial">Arial</option>
            <option value="Helvetica">Helvetica</option>
            <option value="Times New Roman">Times New Roman</option>
          </select>
        </div>
        
        <div class="property-item">
          <label>字号:</label>
          <input v-model="fontSize" type="number" placeholder="字号" />
        </div>
        
        <div class="property-item">
          <label>X 位置:</label>
          <input v-model="x" type="number" placeholder="X 位置" />
        </div>
        
        <div class="property-item">
          <label>Y 位置:</label>
          <input v-model="y" type="number" placeholder="Y 位置" />
        </div>
        
        <div class="property-status">文字已选中</div>
      </div>
      <div v-else class="no-selection">
        请在画布中选择一个元素
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'

// 定义画布引用
const canvas = ref(null)
// 定义文本元素数组
const textElements = ref([
  {
    id: 1,
    text: 'Hello, World!',
    fontFamily: 'Arial',
    fontSize: 30,
    x: 100,
    y: 100,
    isSelected: false
  }
])
// 当前选中的文本元素索引
const selectedTextIndex = ref(-1)
// 当前编辑的文本属性（用于右侧面板）
const text = ref('Hello, World!')
const fontFamily = ref('Arial')
const fontSize = ref(30)
const x = ref(100)
const y = ref(100)
// 鼠标是否悬停在文字上
const isOverText = ref(false)
// 底图对象
const image = new Image()

// 添加文本的方法
const addText = () => {
  // 创建新的文本元素
  const newX = Math.floor(Math.random() * 400) + 100
  const newY = Math.floor(Math.random() * 300) + 100
  const newId = textElements.value.length > 0 ? Math.max(...textElements.value.map(el => el.id)) + 1 : 1
  
  // 取消之前选中的文本
  if (selectedTextIndex.value !== -1) {
    textElements.value[selectedTextIndex.value].isSelected = false
  }
  
  // 添加新文本元素
  const newElement = {
    id: newId,
    text: '新文本',
    fontFamily: 'Arial',
    fontSize: 30,
    x: newX,
    y: newY,
    isSelected: true
  }
  textElements.value.push(newElement)
  
  // 更新选中索引和编辑面板数据
  selectedTextIndex.value = textElements.value.length - 1
  updateEditingProperties()
  
  // 重新绘制
  const ctx = canvas.value.getContext('2d')
  drawText(ctx)
}

onMounted(() => {
  const ctx = canvas.value.getContext('2d')
  // 加载底图
  image.src =
    'https://www4.bing.com//th?id=OHR.BlueNaxos_ZH-CN7863097040_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp' // 替换为实际的底图路径
  image.onload = () => {
    // 绘制底图
    ctx.drawImage(image, 0, 0, canvas.value.width, canvas.value.height)
    // 绘制文字
    drawText(ctx)
  }
})

// 更新编辑面板属性
const updateEditingProperties = () => {
  if (selectedTextIndex.value !== -1) {
    const selectedElement = textElements.value[selectedTextIndex.value]
    text.value = selectedElement.text
    fontFamily.value = selectedElement.fontFamily
    fontSize.value = selectedElement.fontSize
    x.value = selectedElement.x
    y.value = selectedElement.y
  }
}

// 将编辑面板的属性同步到选中的文本元素
const syncPropertiesToSelectedElement = () => {
  if (selectedTextIndex.value !== -1) {
    const selectedElement = textElements.value[selectedTextIndex.value]
    selectedElement.text = text.value
    selectedElement.fontFamily = fontFamily.value
    selectedElement.fontSize = fontSize.value
    selectedElement.x = x.value
    selectedElement.y = y.value
  }
}

const drawText = (ctx) => {
  // 清除之前的内容
  ctx.clearRect(0, 0, canvas.value.width, canvas.value.height)
  // 绘制底图
  ctx.drawImage(image, 0, 0, canvas.value.width, canvas.value.height)
  
  // 绘制所有文本元素
  textElements.value.forEach(element => {
    // 设置文字样式
    ctx.font = `${element.fontSize}px ${element.fontFamily}`
    // 根据选中状态设置文字颜色
    ctx.fillStyle = element.isSelected ? 'red' : 'black'
    // 绘制文字
    ctx.fillText(element.text, element.x, element.y)
    
    // 如果文字被选中，绘制边框
    if (element.isSelected) {
      // 获取文字宽度
      const textWidth = ctx.measureText(element.text).width
      // 绘制选中边框
      ctx.strokeStyle = 'blue'
      ctx.lineWidth = 2
      ctx.strokeRect(element.x - 5, element.y - element.fontSize + 5, textWidth + 10, element.fontSize + 10)
    }
  })
}

// 监听文字、字体、字号、位置的变化，同步到选中元素并重新绘制
watch([text, fontFamily, fontSize, x, y], () => {
  syncPropertiesToSelectedElement()
  const ctx = canvas.value.getContext('2d')
  drawText(ctx)
})

// 监听文本元素数组的变化，重新绘制
watch(textElements, () => {
  const ctx = canvas.value.getContext('2d')
  drawText(ctx)
}, { deep: true })

// 检查点击位置是否在指定文本元素区域内
const isPointInTextArea = (element, mouseX, mouseY) => {
  const ctx = canvas.value.getContext('2d')
  ctx.font = `${element.fontSize}px ${element.fontFamily}`
  const textWidth = ctx.measureText(element.text).width
  const textHeight = element.fontSize
  
  // 文字区域的边界
  const textLeft = element.x
  const textRight = element.x + textWidth
  const textTop = element.y - textHeight
  const textBottom = element.y
  
  // 检查点击位置是否在文字区域内
  return mouseX >= textLeft && mouseX <= textRight && mouseY >= textTop && mouseY <= textBottom
}

// 查找鼠标位置下的文本元素
const findTextElementAtPosition = (mouseX, mouseY) => {
  // 从后向前检查（后添加的元素优先选中）
  for (let i = textElements.value.length - 1; i >= 0; i--) {
    if (isPointInTextArea(textElements.value[i], mouseX, mouseY)) {
      return i
    }
  }
  return -1
}

// 处理鼠标按下事件
const handleMouseDown = (event) => {
  const rect = canvas.value.getBoundingClientRect()
  const mouseX = event.clientX - rect.left
  const mouseY = event.clientY - rect.top
  
  // 查找点击位置的文本元素
  const clickedIndex = findTextElementAtPosition(mouseX, mouseY)
  
  // 取消之前选中的文本
  if (selectedTextIndex.value !== -1) {
    textElements.value[selectedTextIndex.value].isSelected = false
  }
  
  // 更新选中状态
  if (clickedIndex !== -1) {
    textElements.value[clickedIndex].isSelected = true
    selectedTextIndex.value = clickedIndex
    updateEditingProperties()
  } else {
    selectedTextIndex.value = -1
  }
  
  // 重新绘制
  const ctx = canvas.value.getContext('2d')
  drawText(ctx)
}

// 处理鼠标移动事件
const handleMouseMove = (event) => {
  const rect = canvas.value.getBoundingClientRect()
  const mouseX = event.clientX - rect.left
  const mouseY = event.clientY - rect.top
  
  // 检查鼠标是否悬停在任何文字上
  const hoverIndex = findTextElementAtPosition(mouseX, mouseY)
  isOverText.value = hoverIndex !== -1
}

// 处理鼠标松开事件
const handleMouseUp = () => {
  // 可以在这里添加拖拽结束后的逻辑
}
</script>

<style scoped>
.editor-container {
  display: flex;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.left-panel {
  width: 200px;
  padding: 15px;
  border-right: 1px solid #ddd;
  background-color: #f5f5f5;
}

.center-panel {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f9f9f9;
  padding: 20px;
  overflow: auto;
}

.right-panel {
  width: 250px;
  padding: 15px;
  border-left: 1px solid #ddd;
  background-color: #f5f5f5;
  overflow-y: auto;
}

h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.component-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.component-item {
  padding: 8px 12px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.component-item:hover {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.property-panel {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.property-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.property-item label {
  font-size: 14px;
  color: #666;
}

.property-item input,
.property-item select {
  padding: 6px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 100%;
}

.property-status {
  margin-top: 15px;
  padding: 8px;
  background-color: #f0f9eb;
  color: #67c23a;
  border-radius: 4px;
  text-align: center;
}

.no-selection {
  color: #999;
  text-align: center;
  padding: 20px 0;
}

canvas {
  border: 1px solid #ddd;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>
